package agent_store

import (
	"context"
	"encoding/json"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/app/respx"
	"xialou_platform/app/tools"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StoreAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewStoreAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) StoreAddLogic {
	return StoreAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StoreAddLogic) StoreAdd(req *types.StoreBody) (resp *types.StoreAddResp, err error) {

	// 健身类，没有资质上传
	if len(req.Qualifications) < 2 {
		req.Qualifications = append(req.Qualifications, "")
	}

	agentId, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return nil, err
	}
	agentParam, err := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{Id: agentId})
	if err != nil {
		return nil, errorx.NewMsgCodeError(errorx.UnLoginCode, "请重新登录")
	}

	if agentParam.Status != 2 {
		return nil, errorx.NewDefaultError("你的销氪身份未认证，请先认证销氪身份！")
	}

	reqParam, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}
	// 远程Http调用商户API
	bytes, err := tools.RequestOtherPlatform(
		l.svcCtx.Config.XiuXianApi.StoreAdd,
		"POST",
		l.svcCtx.Config.Auth.AccessSecret,
		string(reqParam),
		l.svcCtx.Config.Auth.AccessExpire,
		10000, // admin_users表 下楼系统账户的ID
	)
	if err != nil {
		return nil, err
	}

	var res StoreAddRes
	err = json.Unmarshal(bytes, &res)
	if err != nil {
		logx.Infof("调用%v的新增接口err：%v", req.Platform, err.Error())
		return nil, errorx.NewMsgReasonCodeError(errorx.DefaultCode, "调用新增接口err：%v", err.Error())
	}

	logx.Infof("新增商户: %v", res)
	if res.Code != 200 {
		return nil, errorx.NewCodeReason(res.Code, res.Message)
	}

	storeId := respx.IDParse(res.Data.Id).GetInt64()
	// 记录录入商户记录
	storeAdd, err := l.svcCtx.AgentRpc.StoreAdd(l.ctx, &agentClient.Store{
		Id:              storeId,
		Platform:        req.Platform,
		Name:            req.Name,
		StoreId:         storeId,
		StoreTypeId:     int64(req.StoreType),
		AgentId:         agentId,
		BusinessLicense: req.Qualifications[0],
		IndustryLicense: req.Qualifications[1],
		EquityPrice:     req.ItemPrice,
		StorePhone:      req.Phone,
		SupportTakeaway: req.SupportTakeaway,
		PackingFee:      req.PackingFee,
	})
	if err != nil {
		return nil, err
	}

	req.StoreId = res.Data.Id
	reqByte, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}
	// 添加记录
	_, err = l.svcCtx.AgentRpc.StoreLogAdd(l.ctx, &agentClient.StoreLog{
		StoreId:   storeId,
		Body:      string(reqByte),
		Operation: "add",
		AgentId:   agentId,
	})
	if err != nil {
		return nil, err
	}

	resp = &types.StoreAddResp{
		Id: respx.IDFrom(storeAdd.Id).ToString(),
	}
	return resp, nil
}

type StoreAddRes struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    struct {
		Id string `json:"id"`
	} `json:"data"`
}
